package controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;

@Controller
public class UploadController {
    /**
     * 上传单个文件操作
     * MultipartFile file就是上传的文件
     *
     * @return
     */
    @RequestMapping(value = "/upload.html")
    @ResponseBody
    public String fileUpload1(@RequestParam("file") MultipartFile file, @RequestParam(value = "key1", required = false) String key1,@RequestParam(value = "key2", required = false) String key2) {
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = System.currentTimeMillis() + extName;
        try {
            System.out.println(key1);
            System.out.println(key2);
            //将上传的文件存在E:/upload/下
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:/upload/",
                    fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //上传成功返回原来页面
        return "http://localhost:8080/upload/" + fileName;
    }
    @RequestMapping(value = "/upload2.html")
    @ResponseBody
    public String fileUpload2(@RequestParam("file") MultipartFile file) {
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = System.currentTimeMillis() + extName;
        try {
            //将上传的文件存在E:/upload/下
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:/upload/",
                    fileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //上传成功返回原来页面
        return "{\"error\":0,\"url\":\""+"http://localhost:8080/upload/" + fileName+"\"}";
    }

    @RequestMapping("editor.html")

    public String editor(String desc){
        System.out.println(desc);
        return "kindeditor.jsp";
    }
}
